<template>
  <div class="hello">
    <h1>{{location.name}}</h1>
    <div ref="chartContainer" class="chartContainer"></div>
  </div>
</template>

<script>
import axios from "axios"
//引入echarts折线图
import * as echarts from 'echarts/core';
import { GridComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([GridComponent, LineChart, CanvasRenderer, UniversalTransition]);
import dayjs from "dayjs"//引入dayjs
import { KEY, API_24H } from "@/common/constrants";
import { mapActions, mapState } from "vuex";

export default {
  name: 'HelloWorld',
  computed: {//计算属性
    ...mapState([ //辅助函数
      "location",
      "hour24"
    ])
  },

  watch: {
    location: function () {
      // console.log("_______")
      this.getData();
    }
  },
  created() {
    this.getData();
  },
  methods: {
    ...mapActions([//辅助函数
      'updateHour24Action'
    ]),
    getData() {
      axios.get(API_24H, {
        params: {
          key: KEY,
          location: this.location.id //等价于this.$store.state.location.id

        }
      }).then(res => {
        console.log(res)
        let hour24Data = {
          fxTime: [],//x轴数据
          temp: [],//seriesData
        }
        res.data.hourly.forEach(element => {
          hour24Data.fxTime.push(element.fxTime)
          hour24Data.temp.push(element.temp)
        });
        //当24小时的数据做了变化之后，需要更新到state中   //更新状态
        this.updateHour24Action(hour24Data)//等价于this.$store.dispatch('updateHour24Action',hour24Data)
        // array.map方法
        // 箭头函数写法1
        // let array = this.hourWeatherData.fxTime.map((data)=>{
        //   return dayjs(data).forEach("HH")
        // // })
        // 箭头函数写法2
        // let array = this.hourWeatherData.fxTime.map(data=>dayjs(data).format("HH"))
        // console.log(array)

        this.initChart(
          this.hour24.fxTime.map(data => dayjs(data).format("HH")),
          this.hour24.temp
        )
      })
    },
    // 初始化图表
    initChart(xAxisData, seriesData) {
      var chartDom = this.$refs.chartContainer;
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        xAxis: {
          type: 'category',
          // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          data: xAxisData
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            // data: [150, 230, 224, 218, 135, 147, 260],
            data: seriesData,
            type: 'line'

          }
        ]
      };

      option && myChart.setOption(option);
    }
  }
}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.chartContainer {
  height: 20rem;
}
h1{
  margin: 3rem 0;
}
</style>
